package com.cicadasmall.security.handler;

import cn.hutool.core.util.CharsetUtil;
import cn.hutool.http.HttpStatus;
import com.cicadasmall.common.resp.R;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * RestAuthExceptionEntryPoint
 *
 * @author Jin
 */
@Slf4j
public class RestAuthExceptionEntryPoint implements AuthenticationEntryPoint {

    String accept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9";

    private final ObjectMapper objectMapper;

    public RestAuthExceptionEntryPoint(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
    }

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response,
                         AuthenticationException authException) throws IOException {
        String accept = request.getHeader("Accept");
        response.setCharacterEncoding(CharsetUtil.UTF_8);
        response.setStatus(HttpStatus.HTTP_UNAUTHORIZED);
        PrintWriter printWriter = response.getWriter();
        if (accept.contains(MediaType.APPLICATION_JSON_VALUE)) {
            response.setContentType(MediaType.APPLICATION_JSON_VALUE);
            printWriter.append(objectMapper.writeValueAsString(R
                    .error()
                    .setMessage(authException instanceof InsufficientAuthenticationException ? "请求未授权或令牌已过期!（" + authException.getMessage() + "）" : authException.getMessage())));
        } else {
            response.setContentType(MediaType.TEXT_HTML_VALUE);
            printWriter.append("未授权！");
        }
        printWriter.close();
    }
}
